<?php

require_once(dirname(__FILE__) . '/appconf.php');

class MemberCenter extends Site {

    function setup() {
        $this->run_modes('invite', 'report', 'attention', 'points', 'blog_do', 'blog');
        $this->start_mode('invite');
        $this->selfurl = '/member_center.php';
        $this->pagesize = 3;
        parent::setup();
        include("common.php");
    }

    function cgiapp_prerun($rm = '') {
        $this->Member = getModel('Model_Member');
        $this->Product = getModel('Model_Product');
        $this->Product_application = getModel('Model_ProductApplication');
        $this->Member_application = getModel('Model_MemberApplication');
        $this->Event_application = getModel('Model_EventApplication');
        $this->Lookup = getModel('Model_Lookup');
        $this->Member_like = getModel('Model_MemberLike');
        $this->ProductReports = getModel('Model_ProductReports');
        $this->member = $this->s_param('memberData');
        $this->email_obj = getLibClass('itrialEmail');
        $this->Member_center = getModel('Model_MemberCenter');
        $this->Points = getModel('Model_Points');
        $this->BlogCategory = getModel('Model_BlogCategory');
        require_once(LIB_PATH . '/Common/HTMLPurifier/HTMLPurifier.standalone.php');
        parent::cgiapp_prerun();
    }

    function action_invite() {
        if (empty($this->member)) {
            showMsgCode(NO_LOGIN, '/member.php?action=login&toURL=member_center.php?action=invite');
        }
        $_msg = $this->get_q('msg', ''); //顯示消息
        $msg = base64_decode(base64_decode($_msg));
        //會員信息
        $member = $this->Member_center->get_member($this->member);
        $this->Member_center->get_expiration_point($member['id']);
        $this->Member_center->get_unfreeze_point($member['id']);

        $t = intval($this->get_q('t', 0, 'int')); //下拉選項
        $_invite_arr = $this->Member_center->get_invite_type($t);

        $c = empty($_invite_arr['c']) ? 0 : $_invite_arr['c']; //選項類型 0全部 1產品 2活動
        $type = empty($_invite_arr['type']) ? 0 : $_invite_arr['type']; //產品或活動狀態  0全部 2 成功邀請 1 審核中、拒絕

        if ($c == 1) {
            $data = $this->Member_center->productResult($member['id'], $type);
            $this->tmpl_assign('data', $data);
        } elseif ($c == 2) {
            $data = $this->Member_center->eventResult($member['id'], $type);
            $this->tmpl_assign('data', $data);
        } else {
            $dataA = $this->Member_center->productResult($member['id'], $type);
            $dataB = $this->Member_center->eventResult($member['id'], $type);
            $this->tmpl_assign('dataA', $dataA);
            $this->tmpl_assign('dataB', $dataB);
        }

        $select = array(0 => "全部", 1 => '成功獲邀產品', 2 => '已申請的產品', 3 => '已接受邀請產品', 4 => '成功獲邀活動', 5 => '已參加的活動', 6 => '已接受邀請活動');

        $_isexp = $this->Member_center->get_member_status($this->member); //判斷是否需顯示成為體驗團按鈕

        $this->tmpl_assign('isexp', $_isexp);
        $this->tmpl_assign('select', $select);
        $this->tmpl_assign('msg', $msg);
        $this->tmpl_assign('t', $t);
        $this->tmpl_assign('c', $c);
        $this->tmpl_assign('member', $member);
        $this->tmpl_assign('memberData', $this->member);
        $this->tmpl_assign('thisUrl', urlencode('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']));
        return $this->load_tmpl("mc_invite.php");
    }

    function action_report() {
        if (empty($this->member)) {
            showMsgCode(NO_LOGIN, '/member.php?action=login&toURL=member_center.php?action=invite');
        }
        //會員信息
        $member = $this->Member_center->get_member($this->member);
        $this->Member_center->get_expiration_point($member['id']);
        $this->Member_center->get_unfreeze_point($member['id']);

        $option = intval($this->get_q('option', 0, 'int'));
        $page = intval($this->get_q('page', 1, 'int'));
        $more_type = intval($this->get_q('more_type', 0, 'int'));
        $pagesize1 = intval($this->get_q('ps1', 4, 'int'));
        $pagesize2 = intval($this->get_q('ps2', 2, 'int'));


        $submit_reports = $this->Member_center->get_report_type($member['id'], $option, $page, $pagesize1);
       
       

        $reject_reports = $this->Member_center->get_reject_report($member['id'], $page, $pagesize1);

        $my_reports_res = $this->ProductReports->getReportsList(0, $member['id'], 0, "TB1.addtime desc", $page, $pagesize2, 1);
        $my_reports = $this->Member_center->get_my_reports($my_reports_res);
        //echo '<pre>' . var_export($my_reports, 1) . '</pre>';

        $my_like_reports_res = $this->Member_like->getMemberLike($member['id'], 'report', 0, $page, $pagesize2);
        $my_like_reports_num = $this->Member_like->getMemberLikeNum($member['id'], 'report', 0);



        $my_like_reports = $this->Member_center->get_my_like_reports($my_like_reports_res);

        $pagelist1 = showPage($submit_reports['pageinfo']['total'], $pagesize1, $page, '/member_center.php?action=report&option=' . $option . '&more_type=' . $more_type . '&ps1=' . $pagesize1);
        $pagelist4 = showPage($reject_reports['pageinfo']['total'], $pagesize1, $page, '/member_center.php?action=report&option=' . $option . '&more_type=' . $more_type . '&ps1=' . $pagesize1);
        $pagelist2 = showPage($my_reports_res['pageinfo']['total'], $pagesize2, $page, '/member_center.php?action=report&option=' . $option . '&more_type=' . $more_type . '&ps2=' . $pagesize2);
        $recommen_count = $my_like_reports_num['total'];
        $pagelist3 = showPage($recommen_count, $pagesize2, $page, '/member_center.php?action=report&option=' . $option . '&more_type=' . $more_type . '&ps2=' . $pagesize2);
        //$submit_reports_count = db_query_count('member_application', 'status=1 and mid=' . $member['id']); //判斷是否有邀請
        $_isexp = $this->Member_center->get_member_status($this->member); //判斷是否需顯示成為體驗團按鈕
        $this->tmpl_assign('isexp', $_isexp);
        $select = array(0 => '全部', 2 => '未提交', 1 => '已提交');
        $this->tmpl_assign('select', $select);
        $this->tmpl_assign('option', $option);
        $this->tmpl_assign('warntxt', "您已錯過報告的提交時間，我們有權不刊登您的報告！");
        $this->tmpl_assign('more_type', $more_type);
        $this->tmpl_assign('pagelist1', $pagelist1);
        $this->tmpl_assign('pagelist2', $pagelist2);
        $this->tmpl_assign('pagelist3', $pagelist3);
        $this->tmpl_assign('pagelist4', $pagelist4);
        $this->tmpl_assign('member', $member);
        $this->tmpl_assign('submit_reports', $submit_reports);
        $this->tmpl_assign('reject_reports', $reject_reports);
        $this->tmpl_assign('my_reports', $my_reports);
        $this->tmpl_assign('my_reports_res', $my_reports_res);

        $this->tmpl_assign('my_like_reports', $my_like_reports);
        $this->tmpl_assign('my_like_reports_num', $my_like_reports_num);

        $this->tmpl_assign('memberData', $this->member);
        $this->tmpl_assign('thisUrl', urlencode('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']));
        //$this->tmpl_assign('submit_reports_count', $submit_reports_count);
        return $this->load_tmpl("mc_report.php");
    }

    function action_attention() {
        if (empty($this->member)) {
            showMsgCode(NO_LOGIN, '/member.php?action=login&toURL=member_center.php?action=invite');
        }
        //會員信息
        $member = $this->Member_center->get_member($this->member);
        $this->Member_center->get_expiration_point($member['id']);
        $this->Member_center->get_unfreeze_point($member['id']);

        $user_list1 = $this->Member_like->getAllLikeMember($member['id'], 0, 1, 200);
        if (!empty($user_list1)) {
            foreach ($user_list1 as $k => $v) {
                $user_list1[$k]['_photo_url'] = imore_avatar($v['photo']);
            }
        }

        $user_list2 = $this->Member_like->getAllLikeMember(0, $member['id'], 1, 200);
        if (!empty($user_list2)) {
            foreach ($user_list2 as $k => $v) {
                $_mem = $this->Member->getMember($v['mid']);
                $user_list2[$k]['_name'] = $_mem['result'][0]['username'];
                $user_list2[$k]['_photo_url'] = imore_avatar($_mem['result'][0]['photo']);
            }
        }

        //echo '<pre>'.var_export($user_list1,1).'</pre>';

        $_isexp = $this->Member_center->get_member_status($this->member); //判斷是否需顯示成為體驗團按鈕

        $this->tmpl_assign('isexp', $_isexp);
        $this->tmpl_assign('member', $member);
        $this->tmpl_assign('user_list1', $user_list1);
        $this->tmpl_assign('user_list2', $user_list2);
        $this->tmpl_assign('memberData', $this->member);
        $this->tmpl_assign('thisUrl', urlencode('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']));
        return $this->load_tmpl("mc_attention.php");
    }

    function action_points() {
        if (empty($this->member)) {
            showMsgCode(NO_LOGIN, '/member.php?action=login&toURL=member_center.php?action=invite');
        }
        //會員信息
        $member = $this->Member_center->get_member($this->member);
        $this->Member_center->get_expiration_point($member['id']);
        $this->Member_center->get_unfreeze_point($member['id']);

        $now = getdate();
        $time_str1 = "-06-30 23:59:59";
        $time_str2 = "-12-31 23:59:59";
        $start_time = $end_time = $expire_time = "";
        if (time() >= strtotime($now['year'] . $time_str1) || strtotime("2013-07-01 00:00:00") >= strtotime($now['year'] . $time_str1)) {
            $expire_time = intval($now['year']) . $time_str2;
            $start_time = (intval($now['year']) - 1) . $time_str2;
            $end_time = $now['year'] . $time_str1;
        } else {
            $expire_time = $now['year'] . $time_str1;
            $start_time = (intval($now['year']) - 1) . $time_str1;
            $end_time = (intval($now['year']) - 1) . $time_str2;
        }

        $points_arr = $this->Points->get_points_detail($member['id'], $start_time, $end_time, 1, 0);
        $surplus_points = $total_points = 0;
        if (!empty($points_arr)) {
            foreach ($points_arr as $value) {
                $surplus_points += intval($value['surplus_points']);
                $total_points += intval($value['total_points']);
            }
        }
        $notices = array(
            "surplus_points" => $surplus_points,
            "total_points" => $total_points,
            "start_time" => date("Y-m-d H:i:s", strtotime($start_time) + 1),
            "end_time" => $end_time,
            "expire_time" => $expire_time
        );

        $start_date = date("Y-m-d H:i:s", (time() - 30 * 24 * 3600));
        $records_add = $this->Points->get_points_record($this->member['id'], "", 1, $start_date, date("Y-m-d H:i:s", time()));
        $records_subtract = $this->Points->get_points_record($this->member['id'], "", 0, $start_date, date("Y-m-d H:i:s", time()));

        //echo '<pre>' . var_export($records, 1) . '</pre>';
        $_isexp = $this->Member_center->get_member_status($this->member); //判斷是否需顯示成為體驗團按鈕
        $this->tmpl_assign('isexp', $_isexp);
        $this->tmpl_assign('member', $member);
        $this->tmpl_assign('notices', $notices);
        $this->tmpl_assign('points_arr', $points_arr);
        $this->tmpl_assign('records_add', $records_add);
        $this->tmpl_assign('records_subtract', $records_subtract);
        $this->tmpl_assign('memberData', $this->member);
        $this->tmpl_assign('thisUrl', urlencode('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']));
        return $this->load_tmpl("mc_points.php");
    }

    function action_blog_do() {
        if (empty($this->member)) {
            showMsgCode(NO_LOGIN, '/member.php?action=login&toURL=member_center.php?action=invite');
        }
        $do = intval($this->get_q('do', 1, 'int'));
        $vote_option_data = array('result' => array('滿意度', '抵買度', '舒適度', '清爽度', '持久度', '外型')); //好評  美白度
        switch ($do) {
			case 7://catefory delect
				$id = intval($this->get_q('id', 0, 'int'));
				if($id == 0){
					echo json_encode(array('recode'=>9));
					exit;
				}
				/* $tids = db_query_count('blog_category','topid='.$id);
				$rids = db_query_count('blog_otm_category','cid='.$id);
				if($tids>0){
					echo json_encode(array('recode'=>9,'msg'=>"該分類下尚有子分類，當前無法刪除！"));
					exit;
				}
				if($rids>0){
					echo json_encode(array('recode'=>9,'msg'=>"該分類已被其他blog使用，當前無法刪除！"));
					exit;
				} */
                $res = db_del('blog_category','id='.mysql_escape_string($id).' and mid='.$this->member['id']);
				if($res){
					db_update('blog_category',array('topid'=>0),'topid='.mysql_escape_string($id));
					db_del('blog_otm_category','cid='.mysql_escape_string($id));
					echo json_encode(array('recode'=>1));
				}else{
					echo json_encode(array('recode'=>9,'msg'=>"刪除失敗！"));
				}
                exit;
            case 6://catefory update
				$id = intval($this->get_q('id', 0, 'int'));
				if($id == 0){
					echo json_encode(array('recode'=>9));
					exit;
				}
				$attr = array('name'=>trim(htmlspecialchars($this->get_q('name', ''))));
                $res = db_update('blog_category',$attr,'id='.mysql_escape_string($id).' and mid='.$this->member['id']);
				echo ($res ? json_encode(array('recode'=>1)) : json_encode(array('recode'=>9)));
                exit;
            case 5://catefory new
				$attr = array(
					'mid'=>$this->member['id'],
					'name'=>trim(htmlspecialchars($this->get_q('name', ''))),
					'topid'=>intval($this->get_q('topid', 0, 'int')),
				);
                $res = db_add('blog_category',$attr);
				echo json_encode(array('id'=>$res,'recode'=>1));
                exit;
			case 4://public blog
                $blog_id = intval($this->get_q('bid', 0, 'int'));
                if ($blog_id != 0) {
                    $res = db_update("product_reports", array('is_publish' => 1), "id=" . mysql_escape_string($blog_id) . " and is_blog=1");
                    if ($res)
                        $this->iframeReturn(array('bid' => $blog_id, 'url' => optimize_url('person', 'blog', 'username=' . $this->member['username'] . '&bid=' . $blog_id)), 'callback', array('retcode' => 3, 'msg' => 'blogs public success'));
                }
                break;
            case 3://del blog
                $blog_id = intval($this->get_q('bid', 0, 'int'));
                if ($blog_id != 0) {
                    $res = db_update("product_reports", array('status' => 0), "id=" . mysql_escape_string($blog_id) . " and is_blog=1");
                    if ($res)
                        $this->iframeReturn(array('bid' => $blog_id), 'callback', array('retcode' => 2, 'msg' => 'blogs del success'));
                }
                break;
            case 1://add blog
            case 2://edit blog
            default :
                $issubmit = $this->get_q("issubmit");
                $blog_id = intval($this->get_q('bid', 0, 'int'));
				
                if (!empty($issubmit)) {
                    $attr = array(
                        'is_blog' => 1,
                        'status' => 1,
                        'is_valid' => 1,
                        'is_publish' => intval($this->get_q('p', 1, 'int')),
                        'is_accept' => 1,
                        'mid' => $this->member['id'],
                        'title' => trim(htmlspecialchars($this->get_q('title', ''))),
                        'agegroup' => intval($this->get_q('age', 1, 'int')),
                        'body_skin' => intval($this->get_q('skin', 1, 'int')),
                        'well' => intval($this->get_q('well', 0, 'int')),
                    );
					
                    if (empty($attr['title']))
                        $this->iframeReturn(null, 'callback', array('retcode' => 2, 'msg' => 'title is null!'));

                    $config = HTMLPurifier_Config::createDefault();
                    $config->set('HTML.TargetBlank', true);
                    ////保留指定標籤，和標籤的屬性，其它全部過濾
                    $config->set('HTML.Allowed', 'span[style],em,strong,img[src|align|height|width|alt],br,b,p,div[style]');
                    $HTMLPurifierObj = new HTMLPurifier($config);
                    $attr['body'] = htmlspecialchars($HTMLPurifierObj->purify($this->get_q('content', '')));
                    if (empty($attr['body']))
                        $this->iframeReturn(null, 'callback', array('retcode' => 3, 'msg' => 'body is null!'));
                    for ($i = 1; $i <= count($vote_option_data['result']); $i++) {
                        $attr['category_score' . $i] = intval($this->get_q('category_score' . $i, 0, 'int'));
                    }
                    $res2 = $_bid = 0;
                    if ($do == 1) {
                        $attr['addtime'] = date('Y-m-d H:i:s');
                        $res2 = db_add('product_reports', $attr);
                        if ($res2){
							$_bid = $res2;
                            $this->Points->points_record($this->member['id'], "submit_topic", "添加Blogs文章");
						}
                    } else {
                        $attr['lastmodify'] = date('Y-m-d H:i:s');
                        $res2 = db_update('product_reports', $attr, "id=" . mysql_escape_string($blog_id));
						if ($res2){
							$_bid = $blog_id;
						}
                    }
                    if ($res2 && $_bid!=0) {
						$catefory_box = $this->get_q('catefory_box');
						if(!empty($catefory_box) && is_array($catefory_box)){
							foreach($catefory_box as $k=>$v){
								$_c = db_query_count('blog_otm_category','rid='.mysql_escape_string($_bid).' and cid='.mysql_escape_string($v));
								if($_c<1){
									db_add('blog_otm_category',array('rid'=>$_bid,'cid'=>$v));
								}
							}
						}
						
                        $_rt = $attr['is_publish'] == 0 ? 4 : 1;
                        $this->iframeReturn(null, 'callback', array('retcode' => $_rt, 'msg' => 'success'));
                    } else {
                        $this->iframeReturn(null, 'callback', array('retcode' => 9, 'msg' => '發表出錯，請稍後重試！'));
                    }
                }

                $my_blogs = $blog_category_checked = array();
                if ($do == 2 && $blog_id != 0) {
                    $my_blogs = $this->ProductReports->getReportsList(0, $this->member['id'], $blog_id, "TB1.id desc", 1, 1, 0, '', 0, 0, 1, 0, 0);
					$blog_category_checked_arr = $this->BlogCategory->getCategoryByReport(array('rid' => $blog_id));
					if(!empty($blog_category_checked_arr)){
						foreach($blog_category_checked_arr as $k=>$v){
							$blog_category_checked[] = $v['cid'];
						}
					}
                }
                $kvcobj = getCache('mc_blog_add', array('expire' => KVC_EXPIRE));
                $agegroup = $kvcobj->get('agegroup');
                if (!$agegroup) {
                    $agegroup = $this->Lookup->getLookup('agegroup'); //年齡段
                    $kvcobj->set('agegroup', $agegroup);
                }
                $face_skin = $kvcobj->get('face_skin');
                if (!$face_skin) {
                    $face_skin = $this->Lookup->getLookup('face_skin'); //膚質
                    $kvcobj->set('face_skin', $face_skin);
                }
                $product_reports_well = $kvcobj->get('product_reports_well');
                if (!$product_reports_well) {
                    $product_reports_well = $this->Lookup->getLookup('product_reports_well'); //滿意度  很好、好
                    $kvcobj->set('product_reports_well', $product_reports_well);
                }

                $blog_category = $this->BlogCategory->getList(array('mid' => $this->member['id']));
                $blog_category_list = $blog_category_list_n = $bls_n = array();
                if (!empty($blog_category)) {
                    $this->foreach_blog_category($blog_category, $blog_category_list, $blog_category_list_n , $bls_n);
                }
				
                //echo '<pre>' . var_export($blog_category_list_n, 1) . '</pre>';


                $_isexp = $this->Member_center->get_member_status($this->member); //判斷是否需顯示成為體驗團按鈕
                $this->tmpl_assign('isexp', $_isexp);
                $this->tmpl_assign('do', $do);
                $this->tmpl_assign('bid', $blog_id);
                $this->tmpl_assign('my_blogs', $my_blogs);
                $this->tmpl_assign('agegroup', $agegroup);
                $this->tmpl_assign('face_skin', $face_skin);
                $this->tmpl_assign('product_reports_well', $product_reports_well);
                $this->tmpl_assign('vote_option_data', $vote_option_data);
                $this->tmpl_assign('bls_n', $bls_n);
                $this->tmpl_assign('blog_category_list', $blog_category_list);
                $this->tmpl_assign('blog_category_checked', $blog_category_checked);
                $this->tmpl_assign('blog_category_list_n', $blog_category_list_n);
                $this->tmpl_assign('memberData', $this->member);
                $this->tmpl_assign('thisUrl', urlencode('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']));
                return $this->load_tmpl("mc_blog_add.php");
        }
    }

    function action_blog() {
        if (empty($this->member)) {
            showMsgCode(NO_LOGIN, '/member.php?action=login&toURL=member_center.php?action=invite');
        }
        //會員信息
        $member = $this->Member_center->get_member($this->member);
        $this->Member_center->get_expiration_point($member['id']);
        $this->Member_center->get_unfreeze_point($member['id']);

        $option = intval($this->get_q('option', 0, 'int'));
        $page = intval($this->get_q('page', 1, 'int'));

        $my_blogs = $this->ProductReports->getReportsList(0, $member['id'], 0, "TB1.addtime desc", $page, 5, 0, '', 0, 0, 1, 0, $option);
        foreach ($my_blogs['result'] as $k => $v) {
            $_body = htmlspecialchars_decode($v['body']);
            $my_blogs['result'][$k]['body'] = wordscut(strip_tags($_body), 150);
            $my_blogs['result'][$k]['title'] = wordscut($v['title'], 20);
            //$my_blogs['result'][$k]['time'] = ($v['lastmodify'] && strtotime($v['lastmodify']) >0)?$v['lastmodify']:$v['addtime'];
            $my_blogs['result'][$k]['time'] = $v['addtime'];
            $img_array = array();
            preg_match_all('/<img.*?src=\"\/(.*?)\".*?>/i', $_body, $img_array, PREG_PATTERN_ORDER);
            $img_array = array_unique($img_array[1]);
            if (!empty($img_array)) {
                foreach ($img_array as $k1 => $v1) {
                    $my_blogs['result'][$k]['pic'][$k1] = showphoto($v1, 163, 102);
                    if ($k1 >= 2)
                        break;
                }
            }
        }

        $pagelist = showPage($my_blogs['pageinfo']['total'], 5, $page, '/member_center.php?action=blog&option=' . $option);
        $_isexp = $this->Member_center->get_member_status($this->member); //判斷是否需顯示成為體驗團按鈕
        $select = array(0 => '全部', 1 => '已發佈', 2 => '草稿');

        $this->tmpl_assign('isexp', $_isexp);
        $this->tmpl_assign('select', $select);
        $this->tmpl_assign('option', $option);
        $this->tmpl_assign('pagelist5', $pagelist);
        $this->tmpl_assign('member', $member);
        $this->tmpl_assign('my_blogs', $my_blogs);
        $this->tmpl_assign('memberData', $this->member);
        $this->tmpl_assign('thisUrl', urlencode('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']));
        return $this->load_tmpl("mc_blog.php");
    }

    function foreach_blog_category($blog_category, &$blog_category_list,&$blog_category_list_n, &$bls_n, $blank_space_i=0) {
        foreach ($blog_category as $key => $value) {
            $bls = '';
            for ($index = 0; $index < $blank_space_i; $index++) {
                $bls .= "　";
            }
            $blog_category_list[$key] = $value['name'];
            $blog_category_list_n[$key] = $bls . $value['name'];
			$bls_n[$key] = $blank_space_i;
            if (!empty($value['sub_category']) && is_array($value['sub_category'])) {
                $blank_space_i_temp = $blank_space_i+1;
                $this->foreach_blog_category($value['sub_category'], $blog_category_list,$blog_category_list_n,$bls_n, $blank_space_i_temp);
            }
        }
    }

}

$webapp = new MemberCenter();
$webapp->run();
?>